package com.example.mapsapp;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMarkerClickListener;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.maps.GeoPoint;

import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Find_Favorite extends Activity implements View.OnClickListener, LocationListener, OnMarkerClickListener {
  private GoogleMap maps;
  LatLng lati;
  static String robin;
  double latitude= 0.0, longtitude= 0.0;
  Button btn;
  EditText text;
  String address;
  
	private LocationManager locationManager;
	private static final long MIN_TIME = 400;
	private static final float MIN_DISTANCE = 1000;

	public static ArrayList<String> list_list = new ArrayList<String>();
	public static ArrayAdapter<String> adapter1;
  
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_find__favorite);
		maps = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
		text = (EditText)findViewById(R.id.txtLocation);
		btn = (Button)findViewById(R.id.findFavorite);
		btn.setOnClickListener(this);
		maps.setOnMarkerClickListener(this);
	   Intent intent = getIntent();
	   String aid = intent.getStringExtra("location");
	   String joker  = intent.getStringExtra("name");
	   System.out.println("please print this " +aid);
	   if (aid !=null)
	   {
		   getFromLocation(aid);
		   lati = new LatLng(latitude,longtitude);
			maps.setMapType(GoogleMap.MAP_TYPE_NORMAL);
			CameraUpdate upd = CameraUpdateFactory.newLatLngZoom(lati,15);
			maps.animateCamera(upd);
			maps.addMarker(new MarkerOptions().position(lati).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)).title(joker+"'s Location" ));
	   }
	    
	}
	@Override
	public void onClick(View v){

		switch (v.getId()){
			case R.id.findFavorite:
				address = text.getText().toString();
				getFromLocation(address);
				getPosition(address);
				break;
			
		}
	}
	public  void getPosition(String UEaddress) {
		lati = new LatLng(latitude,longtitude);
		maps.setMapType(GoogleMap.MAP_TYPE_NORMAL);
		CameraUpdate upd = CameraUpdateFactory.newLatLngZoom(lati,15);
		maps.animateCamera(upd);
		maps.addMarker(new MarkerOptions().position(lati).title("Search: " + address));
	
	}
	
	@Override
	protected void onResume(){
		super.onResume();
		
		if(this.getIntent().hasExtra("location")){
			System.out.println("LOC: " + this.getIntent().getStringExtra("location"));
			
			getFromLocation(this.getIntent().getStringExtra("location"));
			
		}
		
	}
	
	private void getFromLocation(String address)
    {
          

        Geocoder geoCoder = new Geocoder(this, Locale.getDefault());    
        try 
        {
            List<Address> addresses = geoCoder.getFromLocationName(address , 1);
            if (addresses.size() > 0) 
            {            
                GeoPoint p = new GeoPoint(
                        (int) (addresses.get(0).getLatitude() * 1E6), 
                        (int) (addresses.get(0).getLongitude() * 1E6));

                latitude=p.getLatitudeE6()/1E6;
                longtitude=p.getLongitudeE6()/1E6;


                }
        }
        catch(Exception ee)
        {

        }
    }

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.map_activity, menu);
	    return true;
	}
	
	  public boolean onOptionsItemSelected(MenuItem item) {
		    switch(item.getItemId())
		    {
		    case R.id.locationOption:
		    	getLocation();
				return true;
		    case R.id.mapHybrid:
		    	mapTypeHybrid();
		    	return true;
	   		case R.id.mapSat:
	    	mapTypeSat();
	    	return true;
	  		case R.id.mapTerrain:
	    	mapTypeTerrain();
	    	return true;
	  		case R.id.mapNormal:
		    	mapTypeNormal();
		    	return true;
			}
			return true;
		}
	
	  public void getLocation(){
		    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this);
	  }
	  
	  public void mapTypeHybrid(){
		  maps.setMapType(GoogleMap.MAP_TYPE_HYBRID);
	  }
	  
	  public void mapTypeSat(){
		  maps.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
	  }
	  
	  public void mapTypeTerrain(){
		  maps.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
	  }
	  
	  public void mapTypeNormal(){
		  maps.setMapType(GoogleMap.MAP_TYPE_NORMAL);
	  }

		@Override
		public void onLocationChanged(Location location) {
		    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
		    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 15);
		    maps.animateCamera(cameraUpdate);
		    locationManager.removeUpdates(this);
		    
		    maps.addMarker(new MarkerOptions()
	    	.title("My Location")
	    	.position(latLng)
	    	.snippet("Coordinates: " + location.getLatitude() + ", " + location.getLongitude())
	    	.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
	    		);
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) { }

		@Override
		public void onProviderEnabled(String provider) { }

		@Override
		public void onProviderDisabled(String provider) { }
		
		  @Override
		    public boolean onMarkerClick(final Marker marker) {

			  if(!marker.getTitle().contains("Search:")){
				  return false;
			  }
			  else{
				 AlertDialog.Builder altDialog= new AlertDialog.Builder((findViewById(R.id.map).getContext()));
				 //altDialog.setTitle("Radius Is Set To: " + radius); 
				 
				 altDialog.setMessage("Add " + marker.getTitle().substring(8) +" to Favorites? ");
				 altDialog.setNeutralButton("Yes", new DialogInterface.OnClickListener() {
				    
				    @Override
				    public void onClick(DialogInterface dialog, int which) {
				     // TODO Auto-generated method stub	
				     Toast.makeText(getApplicationContext(), "Added To Favorites", Toast.LENGTH_LONG).show();
				     robin = marker.getTitle().substring(8);
				     list_list.add(robin);
				     AddFavoriteTask hulk = new  AddFavoriteTask();
				     hulk.execute("greet");
				
				     
				    }
				   });

					AlertDialog alertDialog = altDialog.create();
					alertDialog.show();
			  return true;
			  
			  		
		    }
		
		}
		  
		  
		  
		  
		  public class AddFavoriteTask extends AsyncTask<String, String, String> {
				@Override
				protected String doInBackground(String... params) {
					// TODO: attempt authentication against a network service.
					String response = "";
					ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
					NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
					
					if(networkInfo != null && networkInfo.isConnected())
					{
						ArrayList<NameValuePair> n = new ArrayList<NameValuePair>(1);
						n.add(new BasicNameValuePair("user", Login.user));
						n.add(new BasicNameValuePair("location", robin));
						
						HttpClient httpClient = new DefaultHttpClient();
						HttpPost httppost = new HttpPost("http://softeng.cs.uwosh.edu/students/cs342g2/addFavorite.php");
						try
						{
							httppost.setEntity(new UrlEncodedFormEntity(n));
							ResponseHandler<String> respondHandler = new BasicResponseHandler();
							response = httpClient.execute(httppost, respondHandler);
						}
						catch(Exception e){
							
						}
					}
					return response;
				}
				
		  }
		  
		  
}
